package junit;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.junit.Test;
import org.junit.runner.RunWith;

import com.jweb.framework.junit.JwebJunit4Runner;
import com.jweb.framework.junit.annotation.ContextConfiguration;
import com.jweb.plugins.j2cache.J2Cache;
import com.jweb.plugins.j2cache.bean.CacheObject;

@RunWith(JwebJunit4Runner.class)
@ContextConfiguration(locations = "classpath:app.properties")
public class _TestJ2Cache {
	@Test
	public void test() {
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		do {
			try {
				System.out.print("> ");
				System.out.flush();
				String line = in.readLine().trim();
				if (line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("exit"))
					break;
				String[] cmds = line.split(" ");
				if ("get".equalsIgnoreCase(cmds[0])) {
					CacheObject obj = J2Cache.get(cmds[1], cmds[2]);
					System.out.printf("[%s,%s,L%d]=>%s\n", obj.getRegion(), obj.getKey(), obj.getLevel(), obj.getValue());
				} else if ("set".equalsIgnoreCase(cmds[0])) {
					J2Cache.set(cmds[1], cmds[2], cmds[3]);
					System.out.printf("[%s,%s]<=%s\n", cmds[1], cmds[2], cmds[3]);
				} else if ("evict".equalsIgnoreCase(cmds[0])) {
					J2Cache.evict(cmds[1], cmds[2]);
					System.out.printf("[%s,%s]=>null\n", cmds[1], cmds[2]);
				} else if ("clear".equalsIgnoreCase(cmds[0])) {
					J2Cache.clear(cmds[1]);
					System.out.printf("Cache [%s] clear.\n", cmds[1]);
				} else if ("help".equalsIgnoreCase(cmds[0])) {
					printHelp();
				} else {
					System.out.println("Unknown command.");
					printHelp();
				}
			} catch (ArrayIndexOutOfBoundsException e) {
				e.printStackTrace();
				System.out.println("Wrong arguments.");
				printHelp();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} while (true);
		J2Cache.close();
		System.exit(0);
	}

	private static void printHelp() {
		System.out.println("Usage: [cmd] region key [value]");
		System.out.println("cmd: get/set/evict/quit/exit/help");
	}
}
